package com.hui.platform.falseworkapi.service.base.login.wechat.controller;

import com.hui.platform.falseworkapi.common.security.annotation.SecurityIgnored;
import com.hui.platform.falseworkapi.common.web.annotation.ApiResult;
import com.hui.platform.falseworkapi.service.base.login.wechat.constant.WechatLoginProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.request.AuthWeChatOpenRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 微信登录
 * @author hui
 */
@RestController
@Api(tags = "微信登录")
@ApiResult
@RequestMapping("/oauth/wechat")
@CrossOrigin
public class WechatLoginController {

    @Autowired
    private WechatLoginProperties properties;

    @ApiOperation(value = "获取授权URL")
    @GetMapping("/render")
    @SecurityIgnored
    public String renderAuth(HttpServletResponse response) throws IOException {
        //创建Request
        AuthRequest authRequest = getAuthRequest();
        //生成第三方平台的授权链接
        //这个链接我们可以直接后台重定向跳转，也可以返回到前端后，前端控制跳转。前端控制的好处就是，可以将第三方的授权页嵌入到iframe中，适配网站设计。
        return authRequest.authorize(AuthStateUtils.createState());
    }

    @ApiOperation(value = "微信回调接口")
    @PostMapping("/callback")
    @SecurityIgnored
    public Object login(@ApiParam("用于接收回调参数的实体") @RequestBody AuthCallback callback) {
        AuthRequest authRequest = getAuthRequest();
        return authRequest.login(callback);
    }

    private AuthRequest getAuthRequest() {
        return new AuthWeChatOpenRequest(AuthConfig.builder()
                .clientId(properties.getAppidPc())
                .clientSecret(properties.getAppSecretPc())
                .redirectUri(properties.getRedirectUri())
                .build());
    }
}
